/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package JTCPconnection;

import java.io.*;
import java.util.LinkedList;
import java.util.Queue;

/**
 * 
 * @author M-R-D
 */

public final class TCPsender implements Runnable
{
	private static final int	SLEEP_TIME		= 10000;	//Nanoseconds to sleep if no messages are to be sent

	Thread						_t;
	TCPconnection				_parent;
	boolean						_shuttingDown	= false;
	PrintWriter					_out;

	Queue<String>				_msgQueue;

	public TCPsender(PrintWriter out, TCPconnection parent)
	{
		_parent = parent;
		_msgQueue = new LinkedList<String>();
		_out = out;
		init();
	}

	private void init()
	{
		_t = new Thread(this);
		_t.start();
	}

	public void send(String msg)
	{
		synchronized (_msgQueue)
		{
			_msgQueue.add(msg);
		}
	}

	@Override
	public void run()
	{
		try
		{
			while (!_shuttingDown)
			{
				synchronized (_msgQueue)
				{
					while (!_msgQueue.isEmpty() && !_shuttingDown)
					{
						_out.println(_msgQueue.remove());
					}
				}
				Thread.sleep(0, SLEEP_TIME);
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
			_parent.onConnectionLost();
		}
	}

	@SuppressWarnings("deprecation")
	public void stop()
	{
		//do not care about deprecated
		_msgQueue = new LinkedList<String>(); //Destroy the message queue
		_t.stop();
	}
}
